import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, smsLogin, getUserInfo } from '@/api/user'
import { getMenuList } from '@/api/menu'
import { parseMenuData } from '@/utils/index'
import { constantRoutes } from '@/router'



const state = {
  token: getToken(), // 从缓存中读取初始值
  userInfo: {},
  menus: constantRoutes,
  menuType: 'home'
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步到缓存
    setToken(token)
  },

  removeToken(state) {
    // 删除Vuex的token

    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setMenuList(state, menus) {

    state.menus = menus
  },
  setMenuType(state, menuType) {

    state.menuType = menuType
  }
}
const actions = {

  async login({ commit }, data) {
    // todo: 调用登录接口
    const { token } = await login(data)

    commit('setToken', token)
    sessionStorage.setItem('token', token)
  },
  async smsLogin({ commit }, data) {
    // todo: 调用登录接口
    const { token } = await smsLogin(data)

    commit('setToken', token)
  },


  async getUserInfo({ commit }) {
    const data = await getUserInfo()
    commit('setUserInfo', data)
    return data
  },
  logout({ commit }) {
    commit('removeToken')
    commit('setUserInfo', {})
    //跳转到登录页
    // resetRouter()
  },

  async getMenuList({ commit }) {
    const data = await getMenuList()
    //将所属的子路由赋值
    const allRoutes = parseMenuData(data)
    commit('setMenuList', allRoutes)

  },
  async switchRole({ dispatch }) {
  try {
    await dispatch('getUserInfo');
    await dispatch('getMenuList');
  } catch (error) {
    console.error('切换角色失败:', error);
  }
}
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}